package com.tanhua.server.service;

import com.tan.model.domain.ErrorResult;
import com.tan.model.domain.UserInfo;
import com.tan.model.vo.CountVo;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.LikeUserapi;
import com.tanhua.dubbo.api.UserInfoapi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.Userthread;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoapi userInfoapi;
    @DubboReference
    LikeUserapi likeUserapi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    public void save(UserInfo userInfo) {
        userInfoapi.save(userInfo);
    }

    public void update(MultipartFile headPhoto, long longValue) throws IOException {
      String url =  ossTemplate.uploadFile(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
      System.out.println(url);
      Boolean face =    aipFaceTemplate.face(url);
      if (face){
          userInfoapi.updateavatar(longValue,url);
      }else {
          throw new BusinessException(ErrorResult.faceError());
      }


    }

    public UserInfo getUserInfo(Long userID) {
      UserInfo userInfo = this.userInfoapi.getUserInfo(userID);
      return userInfo;
    }

    public void updateUserInfo(UserInfo userInfo, long longValue) {
        userInfoapi.updateUserInfo(userInfo,longValue);
    }


    public CountVo getCounts() {
        Long userId = Userthread.getUser().getId();
   Integer likecount = Math.toIntExact(redisTemplate.opsForSet().size(Constants.USER_LIKE_SET_KEY + userId));
        // 获取喜欢用户的集合
        Set<String> notLikeUserIds = redisTemplate.opsForSet().members(Constants.USER_LIKE_SET_KEY + userId);

        // 将集合中的字符串转换为 Long 并收集到 Set 中
        Set<Long> notLikeUserIdsLong = notLikeUserIds.stream()
                .map(Long::valueOf)
                .collect(Collectors.toSet());
      CountVo countVo = likeUserapi.getcounts(userId, likecount, notLikeUserIdsLong);
      return countVo;


    }
}
